<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/7/24 下午10:16
 * Description: 小程序相关设置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\mini\controller;

use app\admin\controller\FormBuilder;
use ky\Logger;
use ky\MiniPlatform\Request\ComponentGetPrivacySetting;
use ky\MiniPlatform\Request\ComponentSetPrivacySetting;
use ky\MiniPlatform\Request\WxaModifyDomain;
use ky\MiniPlatform\Request\WxaSetWebViewDomain;
use ky\MiniPlatform\RequestClient;

class Setting extends Base
{
    private $tabList;
    /**
     * @var \app\common\model\MiniSetting
     */
    private $settingM;
    /**
     * @var RequestClient
     */
    private $client;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->settingM = model('miniSetting');
        $this->tabList = [
            'domains' => [
                'title' => '开发/业务域名',
                'href' => url('index', ['name' => 'domains'])
            ],
            'wxpay' => [
                'title' => '微信支付',
                'href' => url('index', ['name' => 'wxpay'])
            ],
            'privacy' => [
                'title' => '隐私保护指引',
                'href' => url('index', ['name' => 'privacy'])
            ]
        ];
        $this->client = new RequestClient();
    }

    /**
     * 设置
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $current_name = input('name', 'domains');
        $setting = $this->settingM->getOneByMap(['mini_id' => $this->miniId, 'name' => $current_name], true, 1);

        if(empty($setting)){
            $data = [];
        }else{
            $data = json_decode($setting['value'], true);
        }

        if(empty($data)){
            switch ($current_name){
                case 'domains':
                    $access_token = $this->getAccessToken();
                    $request = new WxaModifyDomain();
                    $request->setAction('get');
                    $response = $this->client->execute($request, $access_token);
                    if($response['errcode'] == 0){
                        $data = [
                            'request_domain' => implode(';', $response['requestdomain']),
                            'socket_domain' => implode(';', $response['wsrequestdomain']),
                            'upload_domain' => implode(';', $response['uploaddomain']),
                            'download_domain' => implode(';', $response['downloaddomain']),
                            'udp_domain' => implode(';', $response['udpdomain']),
                            'tcp_domain' => implode(';', $response['tcpdomain'])
                        ];
                    }
                    $request = new WxaSetWebViewDomain();
                    $request->setAction('get');
                    $response = $this->client->execute($request, $access_token);
                    if($response['errcode'] == 0) {
                        $data['webview_domain'] = implode(';', $response['webviewdomain']);
                    }
                    break;
            }
        }

        $data['privacy'] = "隐私保护";
        $builder = new FormBuilder();
        switch ($current_name){
            case 'privacy':
                $access_token = $this->getAccessToken();
                $request = new ComponentGetPrivacySetting();
                //$request->setPrivacyVer(1);
                $response = $this->client->execute($request, $access_token);
                if(intval($response['errcode']) !== 0) {
                    $this->error($response['errmsg']);
                }
                //dump($response);exit;
                $data['contact_phone'] = $response['owner_setting']['contact_phone'];
                $data['notice_method'] = $response['owner_setting']['notice_method'];
                $setting_list = [];
                foreach ($response['setting_list'] as $item){
                    $setting_list[] = $item['privacy_key'] . "|" . $item['privacy_text'];
                }
                $data['privacy_ver'] = 2;
                $data['setting_list'] = implode("\r\n", $setting_list);
                $builder->addFormItem('privacy', 'legend', '用户隐私设置', '用户隐私保护指引参数设置')
                    ->addFormItem('contact_phone', 'number', '开发者手机号', '请填写真实手机号',[], 'required')
                    ->addFormItem('notice_method', 'text', '通知方式', '指的是当开发者收集信息有变动时，通过该方式通知用户。这里服务商需要按照实际情况填写，例如通过弹窗或者公告或者其他方式',[], 'required')
                    ->addFormItem('setting_list', 'textarea', '要收集的信息', '一行一对配置，例如：
UserInfo|个人中心显示个人信息
Location|提供最近的服务')
                    ->addFormItem('privacy_ver', 'radio', '更新版本', '更新版本',[1 => '现网版本', 2 => '开发版本'], 'required');
                break;
            case 'domains':
                $builder->addFormItem('domains', 'legend', '服务器域名', '服务器域名')
                    ->addFormItem('request_domain', 'textarea', 'request合法域名', '多个域名使用;隔开')
                    ->addFormItem('socket_domain', 'textarea', 'socket合法域名', '多个域名使用;隔开')
                    ->addFormItem('upload_domain', 'textarea', 'uploadFile合法域名', '多个域名使用;隔开')
                    ->addFormItem('download_domain', 'textarea', 'downloadFile合法域名', '多个域名使用;隔开')
                    ->addFormItem('udp_domain', 'textarea', 'udp合法域名', '多个域名使用;隔开')
                    ->addFormItem('tcp_domain', 'textarea', 'tcp合法域名', '多个域名使用;隔开')
                    ->addFormItem('webview', 'legend', '业务域名', '业务域名')
                    ->addFormItem('webview_domain', 'textarea', '业务域名', '多个域名使用;隔开');
                break;
            default:
                $builder->setTemplate('common/form')
                    ->addFormItem('appid', 'text', 'AppId', 'AppId', [], 'required maxlength=150')
                    ->addFormItem('mchid', 'text', '商户ID', '商户ID', [], 'required maxlength=100')
                    ->addFormItem('p_appid', 'text', '服务商AppId', '如果是服务商模式，需要填写此项', [], ' maxlength=150')
                    ->addFormItem('p_mchid', 'text', '服务商商户ID', '如果是服务商模式，需要填写此项', [], ' maxlength=100')
                    ->addFormItem('key', 'text', '支付秘钥', '支付秘钥', [], 'required maxlength=32 minlength=32')
                    ->addFormItem('cert_path', 'textarea', '支付证书cert', '请在微信商户后台下载支付证书，用记事本打开apiclient_cert.pem，并复制里面的内容粘贴到这里。', [], 'maxlength=20000')
                    ->addFormItem('key_path', 'textarea', '支付证书key', '请在微信商户后台下载支付证书，使用记事本打开apiclient_key.pem，并复制里面的内容粘贴到这里。', [], ' maxlength=20000')
                    ->addFormItem('rsa_path', 'textarea', 'RSA公钥', '企业付款到银行卡需要RSA公钥匙');
                break;
        }
        $builder->setPostUrl(url('savePost', ['name' => $current_name]))
            ->setFormData($data);
        return $builder->show(['tab_nav' => ['tab_list' => $this->tabList, 'current_tab' => $current_name]]);
    }

    /**
     * 设置小程序相关域名
     * @param array $config
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function setDomains($config = []){
        $access_token = $this->getAccessToken();
        //1、设置服务器域名
        $request = new WxaModifyDomain();
        $request->setAction('set');
        $request->setRequestDomain(explode(';', $config['request_domain']));
        $request->setWsRequestDomain(explode(';', $config['socket_domain']));
        $request->setUploadDomain(explode(';', $config['upload_domain']));
        $request->setDownloadDomain(explode(';', $config['download_domain']));
        $response = $this->client->execute($request, $access_token);

        if($response['errcode'] != 0) {
            $this->error($response['errmsg'], '', ['token' => request()->token]);
        }

        //2、设置业务域名
        if(!empty($config['webview_domain']) && $this->miniInfo['principal_name'] !== '个人'){
            $request = new WxaSetWebViewDomain();
            $request->setAction('set');
            $request->setWebViewDomain(explode(';', $config['webview_domain']));
            $response = $this->client->execute($request, $access_token);
            if($response['errcode'] != 0) {
                $this->error($response['errmsg'], '', ['token' => request()->token]);
            }
        }
    }

    public function savePost(){
        $current_name = input('name', 'domains');
        $setting = $this->settingM->getOneByMap(['mini_id' => $this->miniId, 'name' => $current_name], true, 1);

        if(request()->isPost()){
            $post_data = input('post.');
            unset($post_data['__token__']);
            if(empty($setting)){
                $res = $this->settingM->addOne([
                    'mini_id' => $this->miniId,
                    'name' => $current_name,
                    'title' => $this->tabList[$current_name]['title'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }else{
                $res = $this->settingM->updateOne([
                    'id' => $setting['id'],
                    'value' => json_encode($post_data, JSON_UNESCAPED_UNICODE)
                ]);
            }
            if($res){
                switch ($current_name) {
                    case 'domains':
                        $this->setDomains($post_data);
                        break;
                    case 'privacy':
                        $setting_arr = preg_split('/[\r\n]+/', trim($post_data['setting_list'], "\r\n"));
                        $setting_list = [];
                        foreach ($setting_arr as $item){
                            list($k, $v) = explode('|', $item);
                            $setting_list[$k] = $v;
                        }
                        $post_data['setting_list'] = $setting_list;
                        $this->setPrivacySetting($post_data);
                        break;
                }
                $this->success('保存成功');
            }else{
                $this->error('保存失败，请刷新重试', '', ['token' => request()->token()]);
            }
        }
    }

    /**
     * 设置用户隐私保护协议
     * @param array $params
     * @throws \Exception
     * @author: fudaoji<fdj@kuryun.cn>
     */
    private function setPrivacySetting($params = []){
        $access_token = $this->getAccessToken();
        $request = new ComponentSetPrivacySetting();
        $setting_list = [];
        foreach ($params['setting_list'] as $k => $v){
            $v && $setting_list[] = [
                'privacy_key' => $k,
                'privacy_text' => $v
            ];
        }
        $request->setOwnerSetting([
            'contact_phone' => $params['contact_phone'],
            'notice_method' => $params['notice_method']
        ]);
        $request->setSettingList($setting_list);
        $request->setPrivacyVer($params['privacy_ver']);
        $response = $this->client->execute($request, $access_token);
        if(intval($response['errcode']) !== 0) {
            $this->error($response['errmsg']);
        }
    }
}